package com.ziq.zcamp.view.edit;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.SparseArray;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class SupportTopicsEditText extends androidx.appcompat.widget.AppCompatEditText implements TopicsSupportInterface{

    public final static int DEFAULT_SEARCH = -1;
    public final static int NOT_SEARCH = -2;

    private final static String TAG = "SupportTitleEditText";
    public final static String SYMBOL = "#";
    public final static int MAX_TOPICS = 15;

    protected SymbolTriggerCallback mSymbolTriggerCallback;

    //此处带#
    private final SparseArray<String> topics = new SparseArray<>(MAX_TOPICS);

    public SupportTopicsEditText(@NonNull Context context) {
        super(context);
        init();
    }

    public SupportTopicsEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SupportTopicsEditText(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        addTextChangedListener(new SupportTopicsTextWatcher(this));
    }

    /**
     * 设置符号触发器回调
     * @param mSymbolTriggerCallback 回调
     */
    public void setSymbolTriggerCallback(SymbolTriggerCallback mSymbolTriggerCallback) {
        this.mSymbolTriggerCallback = mSymbolTriggerCallback;
    }

    /**
     * 获取话题列表 不带#
     * 如果不存在话题，则返回一个空的列表
     * @return 话题列表
     */
    @NonNull
    public List<String> getTopicList(){
        int size;
        List<String> result = new ArrayList<>(size = topics.size());
        for(int i = 0; i < size; i++) {
            String value = topics.get(topics.keyAt(i)).substring(1);
            if (!result.contains(value)){
                result.add(value);
            }
        }
        return result;
    }

    /**
     * 添加一个话题
     * @param s 话题的模型
     */
    public boolean addTopics(int index , String s){
        if (TextUtils.isEmpty(s.replace(SYMBOL,""))){
            removeTopics(index);
            return false;
        }
        if (topics.indexOfKey(index)>=0){
            topics.put(index,s);
            return false;
        }
        if (topics.size()>=MAX_TOPICS){
            return true;
        }
        topics.put(index,s);
        return false;
    }

    @Override
    public int topicsSize() {
        return topics.size();
    }

    @Override
    public void drawTopicsColor(Editable s) {
        //TODO 很奇怪的地方使用s.clearSpans()会出现数组越界
        //开始之前清除一下之前的信息
        //s.clearSpans();
        ForegroundColorSpan backgroundColor = new ForegroundColorSpan(getCurrentTextColor());
        s.setSpan(backgroundColor,0,s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (topics.size()>0){
            try {
                for(int i = 0; i < topics.size(); i++) {
                    int start = topics.keyAt(i);
                    int end = start + topics.get(start).length();
                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#FFAF8B6C"));
                    s.setSpan(foregroundColorSpan,start,end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void handlerSearch(boolean needSearch) {
        if (!needSearch){
            if (mSymbolTriggerCallback!=null){
                mSymbolTriggerCallback.search(NOT_SEARCH,null);
            }
            return;
        }
        int cursorPosition = getSelectionStart();
        int key;
        int length;

        int selectKey = -1;
        for(int i = 0; i < topics.size(); i++) {
            key = topics.keyAt(i);
            length = topics.get(key).length();
            if (cursorPosition >= key && cursorPosition <= (key+length)){
                selectKey = key;
                break;
            }
        }
        if (selectKey != -1 && mSymbolTriggerCallback!=null){
            String val = topics.get(selectKey);
            mSymbolTriggerCallback.search(selectKey,val.substring(Math.min(1,val.length())));
        }else if (selectKey == -1 && mSymbolTriggerCallback!=null){
            mSymbolTriggerCallback.search(DEFAULT_SEARCH,null);
        }
    }

    @Override
    public void inputProcessingCompleted() {
        if (mSymbolTriggerCallback == null)return;
        boolean isMore = topics.size() >= MAX_TOPICS;
        if (!isMore){
            mSymbolTriggerCallback.overflowTopics(false);
        }
        int cursorPosition = getSelectionStart();
        int key;
        int length;

        int selectKey = -1;
        for(int i = 0; i < topics.size(); i++) {
            key = topics.keyAt(i);
            length = topics.get(key).length();
            if (cursorPosition >= key && cursorPosition <= (key+length)){
                selectKey = key;
                break;
            }
        }
        mSymbolTriggerCallback.overflowTopics(isMore && selectKey == -1);
    }

    /**
     * 删除一个话题
     * @param index 话题的模型
     */
    public void removeTopics(int index){
        //由于重写了equals和hashcode所以只需要一个index就能删除
        topics.remove(index);
    }

    /**
     * 清空话题
     */
    public void clearTopics(){
        topics.clear();
    }

    @Override
    public void apply() {
        if (mSymbolTriggerCallback!=null){
            mSymbolTriggerCallback.apply(this);
        }
    }

    @Override
    public int getSelectionStart() {
        return super.getSelectionStart();
    }

    /**
     * 获取对应的内容文本
     * 此方法会判断结尾处是不是属于话题的一部分，如果是则加一个空格
     * @return str
     */
    public String getTextContent(){
        if (getText()==null)
            return "";
        String str = getText().toString().trim();
        for(int i = 0; i < topics.size(); i++) {
            int start = topics.keyAt(i);
            int end = start + topics.get(start).length();
            if (end==str.length()){
                str += " ";
                return str;
            }
        }
        return str;
    }
}
